package mx.util;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import mx.beans.Console;
import mx.beans.Game;
import mx.beans.Image;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.util.Log;

public class GameParser {

	public final static int LEVEL_UP_SOURCE = 0;
	public final static int IGN_SOURCE = 1;

	private static final String URL_LEVEL_UP = 
			"http://gamers.levelup.com/catalogo/"
			+ "juegos/disponibilidad/preventa/resultados-50/pagina-1/"
			+ "ordenar-calificacion/";

	public static List<Game> getGames(int source) throws IOException {

		switch (source) {
		case LEVEL_UP_SOURCE: // level up
			return parseLevelUp();
			// break;
		case IGN_SOURCE: // ign
			throw new UnsupportedOperationException("IGN");
			// break;
		default:
			throw new UnsupportedOperationException();
		}
	}

	private static List<Game> parseLevelUp() throws IOException {
		// TODO manejar los juegos "duplicados" por los varios tipos de
		// consolass
		Document doc = Jsoup.connect(URL_LEVEL_UP).get();
		Elements elements = doc.getElementsByClass("n_item_cont");
		LinkedList<Game> result = new LinkedList<Game>();
		String prefix = "http://gamers.levelup.com";

		for (Element element : elements) {

			String urlPortrait = element.select("div.image").select("img[src]")
					.get(0).attr("src");

			Elements container = element.select("div.n_container");

			String gameDetailURL = prefix
					+ container.select("p.n_title").get(0).child(0)
							.attr("href");

			String name = container.select("span.game_title").get(0).text();

			List<Console> consoles = new LinkedList<Console>();

			for (Element e : container.select("span.platform")) {
				consoles.add(consoleParseLevelUp(e.text()));
			}

			String publisher = container.select("p.gPublisher").get(0).text();
			publisher = publisher.substring(4, publisher.length());

			String SKU = container.select("p.sku").get(0).text();
			SKU = SKU.substring(4, SKU.length());

			String clasification = container.select("p.clasificacion").get(0)
					.child(0).attr("title");

			String genre = container.select("p.gGenrePlats").get(0).child(0)
					.child(0).text();

			Elements price = element.select("div.price");

			String finalPrice = price.select("p.final_price").text();

			Game toAdd = new Game(SKU, finalPrice, publisher, genre,
					gameDetailURL, name, clasification, consoles);

			toAdd.setSource(LEVEL_UP_SOURCE);
			// TODO Considerar si no debe ser un thread aparte
			toAdd.addPortrait(urlPortrait, consoles.get(0));

		}

		return result;
	}

	private static Console consoleParseLevelUp(String text) {

		if (text.equals("PS3")) {
			return Console.get(Console.PS3);
		} else if (text.equals("Xbox 360")) {
			return Console.get(Console.XBox360);
		} else if (text.equals("WII")) {
			return Console.get(Console.Wii);
		} else if (text.equals("PS Vita")) {
			return Console.get(Console.PSVita);
		} else if (text.equals("3DS")) {
			return Console.get(Console._3DS);
		} else {
			Log.d("consoleParseLevelUp", "Using default console");
			return Console.get(Console.DEFAULT);
		}
	}

	public static void getDetailedInfo(Game game) {

		switch (game.getSource()) {
		case LEVEL_UP_SOURCE: // level up
			getDetailedInfoLevelUp(game);
			break;
		case IGN_SOURCE: // ign
			throw new UnsupportedOperationException("IGN");
			// break;
		default:
			throw new UnsupportedOperationException();
		}
	}

	private static void getDetailedInfoLevelUp(Game game) {
		
		try {
			Document doc = Jsoup.connect(game.getGameDetailURL()).get();
			Element dateContainer = doc.getElementById("ïnfo_game_subHeader");
			// aguas acá!!! notar la "ï" que no es "i", seguramente lo
			// cambiarán
			String releaseDate = dateContainer.child(4).text();
			releaseDate = releaseDate.substring(22, releaseDate.length());

			Element aboutContainer = doc.getElementById("sinopsis");
			String about = aboutContainer.text();

			game.setAbout(about);
			game.setReleaseDate(releaseDate);
		} catch (IOException ioe) {
			// TODO Hacer algo jajajaja, ahorita no sé me ocurre qué
			ioe.printStackTrace();
		}

	}
	
	public static void getImages(Game game) {
		
		switch (game.getSource()) {
		case LEVEL_UP_SOURCE: // level up
			getImagesLevelUp(game);
			// break;
		case IGN_SOURCE: // ign
			throw new UnsupportedOperationException("IGN");
			// break;
		default:
			throw new UnsupportedOperationException();
		}
	}

	private static void getImagesLevelUp(Game game) {
		try {
			LinkedList<Image> result = new LinkedList<Image>();
			Document doc = Jsoup.connect(game.getGameDetailURL()).get();
			Elements elements = doc.getElementsByClass("list");
			Elements imagesList = elements.get(0).children();
			
			for (Element element : imagesList) {
				String imageUrl = element.child(0).attr("href");
				result.add(new Image(imageUrl));
				//TODO checar lo de los threads
			}
			
			game.setImages(result);
		} catch (IOException ioe) {
			// TODO Hacer algo jajajaja, ahorita no sé me ocurre qué
			ioe.printStackTrace();
		}
		
	}

}
